package com.countertack.endtoendstories;

import java.io.File;
import java.io.FileOutputStream;
import java.net.InetAddress;
import java.sql.ResultSet;
import java.util.UUID;

import org.json.JSONObject;

import com.countertack.impala.ImpalaConnector;
import com.countertack.ssh.SSHManager;
import com.countertack.utils.Configuration;
import com.countertack.utils.HttpClientUtils;
import com.countertack.vmware.VMWareConnector;
import com.countertack.vmware.VMWareUtils;
import com.vmware.vim25.mo.VirtualMachine;

public class TaintBasedAnalysis {
	static String vmUser = null;
	static String vmPassword = null;
	static boolean isXpmachine=false;

	public static void main(String[] args) throws Exception {

		/*if (args.length <= 0) {

			System.out.println("configuration details missed !");
			return;
		}
		String configFilePath = args[0];*/
		String configFilePath="C:\\Users\\user\\Desktop\\endtoendautomation\\config.properties";

		// String configFilePath =
		// "C:\\Users\\user\\Desktop\\configm.properties";
		StringBuffer testCaseResult = new StringBuffer();

		Configuration.loadProperties(configFilePath);
		vmUser = Configuration.getProperty("vmuser");
		vmPassword = Configuration.getProperty("vmpassword");

		String uuid = UUID.randomUUID().toString();
		Configuration.loadProperties(configFilePath);

		ImpalaConnector iConnector;

		iConnector = ImpalaConnector
				.createImpalaConnectorInstance(Configuration
						.getProperty("sentinelehost"));

		InetAddress address = InetAddress.getByName(Configuration
				.getProperty("sentinelehost"));
		String sentenelIp = address.getHostAddress();
		System.out.println(address.getHostAddress());
		// connect to esxi and starting virtual machines

		// starting endpoint machine

		VMWareConnector esxiConnector = new VMWareConnector(
				Configuration.getProperty("esxi"));
		// poweredOn
		final VirtualMachine endPointMachine = esxiConnector
				.getVirtualMachineByname(Configuration.getProperty("vmname"));
		String smokeSnapShotName = Configuration
				.getProperty("rootsnapshotname");
		esxiConnector.revertToSnapShort(endPointMachine.getSnapshot()
				.getRootSnapshotList(), smokeSnapShotName);

		System.out.println("Reverting to root snap shot>>>>>"
				+ smokeSnapShotName);

		Thread.sleep(180000);
		System.out.println("power state >>>"
				+ endPointMachine.getRuntime().powerState);

		String endpointMachineStatus = esxiConnector
				.getVirtualMachineStatus(endPointMachine);

		if (endpointMachineStatus == null) {

			System.out.println("Power on  endpoint machine .....");

			esxiConnector.startVirtualMachine(endPointMachine);

			Thread.sleep(600000);

		} else {

			if ("notRunning".equalsIgnoreCase(endpointMachineStatus)) {

				esxiConnector.reStartVirtualMachine(endPointMachine);

				System.out.println("Rebooting endpoint machine .....");

				Thread.sleep(600000);

			}

		}
		
		

		
		String osType = VMWareUtils.getVMOSArchitecture(
				Configuration.getProperty("esxi"),
				Configuration.getProperty("vmname"));
		
		if (osType != null) {

			osType = osType.toLowerCase();

			if (osType.contains("xp")) {

				isXpmachine = true;
			}
		}

		
		String endptIp = Configuration.getProperty("vmip");
		if (endptIp == null || endptIp.trim() == "") {

			endptIp = endPointMachine.getGuest().ipAddress;
		}

		String smartGroupFilterneme = "WIN7";

		if (endPointMachine.getGuest().hostName != null) {

			smartGroupFilterneme = endPointMachine.getGuest().hostName
					.toUpperCase();

			if (smartGroupFilterneme.length() > 10) {

				smartGroupFilterneme = smartGroupFilterneme.substring(0, 10);

			}

			// System.out.println("Fileter name>>>" + smartGroupFilterneme);

		}

		// Creating Manual Group

		String manualRootPayload = "{\"name\":\"Manual Root\",\"rule\":{\"type\":\"manual\"}}";

		String manualRootRes = HttpClientUtils.composePostRequest("https://"
				+ Configuration.getProperty("sentinelehost")
				+ ":9090/api/v1/groups", manualRootPayload);

		// System.out.println("manual root  response>>>" + manualRootRes);

		JSONObject mrObj = new JSONObject(manualRootRes);

		String mrootgrpId = mrObj.optString("id");

		if (mrootgrpId == null || mrootgrpId.trim() == "") {

			System.out
					.println("Creation of  manual root group------------->Fail");
			testCaseResult
					.append("Creation of  manual root group------------->Fail \n");

		} else {

			System.out
					.println("Creation of  manual root group------------->Pass");
			testCaseResult
					.append("Creation of  manual root group------------->Pass \n");

		}
		String payloadProfileWithNoconditions = "{\"type\":\"profile\",\"isNew\":true,\"is_user_visible\":true,\"is_user_editable\":true,\"is_validated_xml\":true,\"xml_string\":\"<cybox:Observables xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns:countertack=\\\"https://www.countertack.com\\\" xmlns:cybox=\\\"http://cybox.mitre.org/cybox-2\\\" xmlns:cyboxCommon=\\\"http://cybox.mitre.org/common-2\\\" xmlns:FileObj=\\\"http://cybox.mitre.org/objects#FileObject-2\\\"  xmlns:ProcessObj=\\\"http://cybox.mitre.org/objects#ProcessObject-2\\\"  xmlns:cyboxVocabs=\\\"http://cybox.mitre.org/default_vocabularies-2\\\" xmlns:example=\\\"http://example.com\\\" xsi:schemaLocation=\\\"http://cybox.mitre.org/cybox-2 http://cybox.mitre.org/XMLSchema/core/2.0.1/cybox_core.xsd     http://cybox.mitre.org/objects#ProcessObject-2 http://cybox.mitre.org/XMLSchema/objects/Process/2.0.1/Process_Object.xsd     http://cybox.mitre.org/default_vocabularies-2 http://cybox.mitre.org/XMLSchema/default_vocabularies/2.0.1/cybox_default_vocabularies.xsd     \\\" cybox_major_version=\\\"2\\\" cybox_minor_version=\\\"0\\\"><cybox:Observable_Package_Source name=\\\"ProfNocon"
				+ uuid
				+ "\\\"></cybox:Observable_Package_Source><cybox:Observable id=\\\"Origins-Profile-Test\\\"><cybox:Description>            Origin Conditions for the profile that detects suspicious activity on the workstation assuming that host in a secure environment.         </cybox:Description>        <cybox:Keywords><cybox:Keyword>Type:Origins</cybox:Keyword></cybox:Keywords><cybox:Observable_Composition operator=\\\"OR\\\"><!-- any process accepts any inbound connection --></cybox:Observable_Composition></cybox:Observable></cybox:Observables>\"}";

		System.out.println("payload>>" + payloadProfileWithNoconditions);

		String profilenocondRes = HttpClientUtils.composePostRequest("https://"
				+ Configuration.getProperty("sentinelehost")
				+ ":9090/api/v1/profiles", payloadProfileWithNoconditions);

		// System.out.println("manual root  response>>>" + manualRootRes);

		JSONObject prnoconObj = new JSONObject(profilenocondRes);

		String nocondproid = prnoconObj.optString("id");

		if (nocondproid == null || nocondproid.trim() == "") {

			System.out
					.println("Creation of  Profile with no conditions------------->Fail");
			testCaseResult
					.append("Creation of  Profile with no conditions------------->Fail \n");

		} else {

			System.out
					.println("Creation of  Profile with no conditions------------->Pass");
			System.out.println("Profile with no conditions ID---------->"
					+ nocondproid);
			testCaseResult
					.append("Creation of  Profile with no conditions------------->Pass \n");
			testCaseResult.append("Profile with no conditions ID---------->"
					+ nocondproid + "\n");

		}

		// creating registry condition
		// iam here
		String payloadregCond = "{\"type\":\"condition\",\"isNew\":true,\"is_user_visible\":true,\"is_user_editable\":true,\"is_validated_xml\":true,\"xml_string\":\"<?xml version=\\\"1.0\\\"?><cybox:Observables xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns:cybox=\\\"http://cybox.mitre.org/cybox-2\\\" xmlns:cyboxCommon=\\\"http://cybox.mitre.org/common-2\\\" xmlns:AddrObj=\\\"http://cybox.mitre.org/objects#AddressObject-2\\\" xmlns:URIObj=\\\"http://cybox.mitre.org/objects#URIObject-2\\\" xmlns:FileObj=\\\"http://cybox.mitre.org/objects#FileObject-2\\\" xmlns:EmailMessageObj=\\\"http://cybox.mitre.org/objects#EmailMessageObject-2\\\" xmlns:cyboxVocabs=\\\"http://cybox.mitre.org/default_vocabularies-2\\\" xmlns:example=\\\"http://example.com/\\\" xsi:schemaLocation=\\\"http://cybox.mitre.org/cybox-2 http://cybox.mitre.org/XMLSchema/core/2.0.1/cybox_core.xsd     http://cybox.mitre.org/objects#URIObject-2 http://cybox.mitre.org/XMLSchema/objects/URI/2.0.1/URI_Object.xsd     http://cybox.mitre.org/objects#FileObject-2 http://cybox.mitre.org/XMLSchema/objects/File/2.0.1/File_Object.xsd     http://cybox.mitre.org/objects#EmailMessageObject-2 http://cybox.mitre.org/XMLSchema/objects/Email_Message/2.0.1/Email_Message_Object.xsd     http://cybox.mitre.org/default_vocabularies-2 http://cybox.mitre.org/XMLSchema/default_vocabularies/2.0.1/cybox_default_vocabularies.xsd   \\\" cybox_major_version=\\\"2\\\" cybox_minor_version=\\\"0\\\" cybox_update_version=\\\"1\\\"><cybox:Observable id=\\\"Rosapa:RegWrite-a585919c-1d07-4d5d-a781-0e58dd56d9f1\\\" xmlns:cybox=\\\"http://cybox.mitre.org/cybox-2\\\"><cybox:Title>Rosapa Registry Write Condition</cybox:Title><cybox:Description>This observable detects any write to registry key  </cybox:Description><cybox:Keywords><cybox:Keyword>Type:Condition</cybox:Keyword></cybox:Keywords><cybox:Event id=\\\"Event-BasicEvent-registry-write-SW-Policies-MSoft-system-certs\\\"><cybox:Actions><cybox:Action id=\\\"Action-BasicEvent-registry-write-SW-Policies-MSoft-system-certs\\\"><cybox:Type xsi:type=\\\"cyboxVocabs:ActionTypeVocab-1.0\\\" xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\">Modify</cybox:Type><cybox:Name xsi:type=\\\"cyboxVocabs:ActionNameVocab-1.0\\\" xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\">Modify Registry Key</cybox:Name><cybox:Associated_Objects><cybox:Associated_Object id=\\\"Registry-key-SW-Policies-MSoft-system-certs\\\"><cybox:Properties xsi:type=\\\"WinRegistryKeyObj:WindowsRegistryKeyObjectType\\\" xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\"><ns2:Key pattern_type=\\\"Regex\\\" xmlns:ns2=\\\"http://cybox.mitre.org/objects#WinRegistryKeyObject-2\\\"></ns2:Key></cybox:Properties><cybox:Association_Type xsi:type=\\\"cyboxVocabs:ActionObjectAssociationTypeVocab-1.0\\\" xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\">Affected</cybox:Association_Type></cybox:Associated_Object></cybox:Associated_Objects></cybox:Action></cybox:Actions></cybox:Event></cybox:Observable></cybox:Observables>\"}";
		String regwritecondRes = HttpClientUtils.composePostRequest("https://"
				+ Configuration.getProperty("sentinelehost")
				+ ":9090/api/v1/profiles", payloadregCond);

		// System.out.println("REG Write>>" + profilenocondRes);

		// creating file write condition

		String payloadfileWrCondition = "{\"type\":\"condition\",\"isNew\":true,\"is_user_visible\":true,\"is_user_editable\":true,\"is_validated_xml\":true,\"xml_string\":\"<?xml version=\\\"1.0\\\"?><cybox:Observables xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns:cybox=\\\"http://cybox.mitre.org/cybox-2\\\" xmlns:cyboxCommon=\\\"http://cybox.mitre.org/common-2\\\" xmlns:AddrObj=\\\"http://cybox.mitre.org/objects#AddressObject-2\\\" xmlns:URIObj=\\\"http://cybox.mitre.org/objects#URIObject-2\\\" xmlns:FileObj=\\\"http://cybox.mitre.org/objects#FileObject-2\\\" xmlns:EmailMessageObj=\\\"http://cybox.mitre.org/objects#EmailMessageObject-2\\\" xmlns:cyboxVocabs=\\\"http://cybox.mitre.org/default_vocabularies-2\\\" xmlns:example=\\\"http://example.com/\\\" xsi:schemaLocation=\\\"http://cybox.mitre.org/cybox-2 http://cybox.mitre.org/XMLSchema/core/2.0.1/cybox_core.xsd     http://cybox.mitre.org/objects#URIObject-2 http://cybox.mitre.org/XMLSchema/objects/URI/2.0.1/URI_Object.xsd     http://cybox.mitre.org/objects#FileObject-2 http://cybox.mitre.org/XMLSchema/objects/File/2.0.1/File_Object.xsd     http://cybox.mitre.org/objects#EmailMessageObject-2 http://cybox.mitre.org/XMLSchema/objects/Email_Message/2.0.1/Email_Message_Object.xsd     http://cybox.mitre.org/default_vocabularies-2 http://cybox.mitre.org/XMLSchema/default_vocabularies/2.0.1/cybox_default_vocabularies.xsd   \\\" cybox_major_version=\\\"2\\\" cybox_minor_version=\\\"0\\\" cybox_update_version=\\\"1\\\"><cybox:Observable id=\\\"Rosapa:FileWrite-f429f38f-e37a-4dd3-98ab-4809d73801f5\\\" xmlns:cybox=\\\"http://cybox.mitre.org/cybox-2\\\"><cybox:Title>Rosapa File Write Condition</cybox:Title><cybox:Description>This condition detects when any processwrites any file to \\\\Users\\\\user\\\\Desktop folder </cybox:Description><cybox:Keywords><cybox:Keyword>Type:Condition</cybox:Keyword></cybox:Keywords><cybox:Event id=\\\"Rosapa-Any-File-Written-to-Desktop\\\"><cybox:Actions><cybox:Action id=\\\"Action-Any-File-Written-to-Desktop\\\"><cybox:Type xsi:type=\\\"cyboxVocabs:ActionTypeVocab-1.0\\\" xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\">Write</cybox:Type><cybox:Name xsi:type=\\\"cyboxVocabs:ActionNameVocab-1.0\\\" xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\">Write to File</cybox:Name><cybox:Associated_Objects><cybox:Associated_Object id=\\\"File-is-Any-File-Written-to-System32\\\"><cybox:Properties xsi:type=\\\"FileObj:FileObjectType\\\" xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\"><FileObj:File_Path pattern_type=\\\"Regex\\\" xmlns:FileObj=\\\"http://cybox.mitre.org/objects#FileObject-2\\\"></FileObj:File_Path></cybox:Properties><cybox:Association_Type xsi:type=\\\"cyboxVocabs:ActionObjectAssociationTypeVocab-1.0\\\" xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\">Affected</cybox:Association_Type></cybox:Associated_Object></cybox:Associated_Objects></cybox:Action></cybox:Actions></cybox:Event></cybox:Observable></cybox:Observables>\"}";
		String filewritecondRes = HttpClientUtils.composePostRequest("https://"
				+ Configuration.getProperty("sentinelehost")
				+ ":9090/api/v1/profiles", payloadfileWrCondition);

		// System.out.println("File Write>>" + filewritecondRes);

		// create inbound condition

		String payLoadInbound = "{\"type\":\"condition\",\"isNew\":true,\"is_user_visible\":true,\"is_user_editable\":true,\"is_validated_xml\":true,\"xml_string\":\"<cybox:Observables xmlns:countertack=\\\"https://www.countertack.com\\\" xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns:cybox=\\\"http://cybox.mitre.org/cybox-2\\\" xmlns:cyboxCommon=\\\"http://cybox.mitre.org/common-2\\\" xmlns:AddressObj=\\\"http://cybox.mitre.org/objects#AddressObject-2\\\" xmlns:PortObj=\\\"http://cybox.mitre.org/objects#PortObject-2\\\" xmlns:SocketAddressObj=\\\"http://cybox.mitre.org/objects#SocketAddressObject-1\\\"  xmlns:NetworkConnectionObj=\\\"http://cybox.mitre.org/objects#NetworkConnectionObject-2\\\" xmlns:example=\\\"http://example.com/\\\" xmlns:ProcessObj=\\\"http://cybox.mitre.org/objects#ProcessObject-2\\\" xmlns:cyboxVocabs=\\\"http://cybox.mitre.org/default_vocabularies-2\\\" xsi:schemaLocation=\\\"http://cybox.mitre.org/cybox-2 http://cybox.mitre.org/XMLSchema/core/2.0.1/cybox_core.xsd     http://cybox.mitre.org/objects#NetworkConnectionObject-2 http://cybox.mitre.org/XMLSchema/objects/Network_Connection/2.0.1/Network_Connection_Object.xsd   http://cybox.mitre.org/objects#ProcessObject-2  http://cybox.mitre.org/XMLSchema/objects/Process/2.0.1/Process_Object.xsd  http://cybox.mitre.org/default_vocabularies-2   http://cybox.mitre.org/XMLSchema/default_vocabularies/2.0.1/cybox_default_vocabularies.xsd   \\\" cybox_major_version=\\\"2\\\" cybox_minor_version=\\\"0\\\"> <cybox:Observable id=\\\"Rosapa:AnyInbound-cc789942-493b-486e-bd9e-5dc5808fb1bf\\\"><cybox:Title>Rosapa Any Inbound Condition</cybox:Title><cybox:Description>            This condition detects when svchost.exe process accepts inbound connection from any remote host.         </cybox:Description>       <cybox:Keywords><cybox:Keyword>Type:Condition</cybox:Keyword></cybox:Keywords>        <cybox:Event id=\\\"Ramana-test-any-inbound\\\"><cybox:Actions><cybox:Action id=\\\"action-test-any-inbound\\\"><cybox:Type xsi:type=\\\"cyboxVocabs:ActionTypeVocab-1.0\\\">Accept</cybox:Type><cybox:Name xsi:type=\\\"cyboxVocabs:ActionNameVocab-1.0\\\">Accept Socket Connection</cybox:Name><cybox:Associated_Objects><cybox:Associated_Object><cybox:Properties xsi:type=\\\"NetworkConnectionObj:NetworkConnectionObjectType\\\"><NetworkConnectionObj:Destination_Socket_Address><SocketAddressObj:IP_Address><AddressObj:Address_Value pattern_type=\\\"Regex\\\"></AddressObj:Address_Value></SocketAddressObj:IP_Address><SocketAddressObj:Port><PortObj:Port_Value pattern_type=\\\"Regex\\\"></PortObj:Port_Value></SocketAddressObj:Port></NetworkConnectionObj:Destination_Socket_Address></cybox:Properties><cybox:Association_Type xsi:type=\\\"cyboxVocabs:ActionObjectAssociationTypeVocab-1.0\\\">Initiating</cybox:Association_Type></cybox:Associated_Object><cybox:Associated_Object><cybox:Properties xsi:type=\\\"ProcessObj:ProcessObjectType\\\"><ProcessObj:Name pattern_type=\\\"Regex\\\"></ProcessObj:Name></cybox:Properties><cybox:Association_Type xsi:type=\\\"cyboxVocabs:ActionObjectAssociationTypeVocab-1.0\\\">Returned</cybox:Association_Type></cybox:Associated_Object></cybox:Associated_Objects></cybox:Action></cybox:Actions></cybox:Event></cybox:Observable></cybox:Observables>\"}";

		String inboundcondRes = HttpClientUtils.composePostRequest("https://"
				+ Configuration.getProperty("sentinelehost")
				+ ":9090/api/v1/profiles", payLoadInbound);

		// System.out.println("Inbound >>" + inboundcondRes);

		// creating profile with conditions

		String payloadProfConditions = "{\"type\":\"profile\",\"isNew\":true,\"is_user_visible\":true,\"is_user_editable\":true,\"is_validated_xml\":true,\"xml_string\":\"<cybox:Observables xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns:countertack=\\\"https://www.countertack.com\\\" xmlns:cybox=\\\"http://cybox.mitre.org/cybox-2\\\" xmlns:cyboxCommon=\\\"http://cybox.mitre.org/common-2\\\" xmlns:FileObj=\\\"http://cybox.mitre.org/objects#FileObject-2\\\" xmlns:ProcessObj=\\\"http://cybox.mitre.org/objects#ProcessObject-2\\\" xmlns:cyboxVocabs=\\\"http://cybox.mitre.org/default_vocabularies-2\\\" xmlns:example=\\\"http://example.com\\\" xsi:schemaLocation=\\\"http://cybox.mitre.org/cybox-2 http://cybox.mitre.org/XMLSchema/core/2.0.1/cybox_core.xsd http://cybox.mitre.org/objects#ProcessObject-2 http://cybox.mitre.org/XMLSchema/objects/Process/2.0.1/Process_Object.xsd http://cybox.mitre.org/default_vocabularies-2 http://cybox.mitre.org/XMLSchema/default_vocabularies/2.0.1/cybox_default_vocabularies.xsd \\\" cybox_major_version=\\\"2\\\" cybox_minor_version=\\\"0\\\"><cybox:Observable_Package_Source name=\\\"Rosapa-AnyInbound-FileRegistry-Write-"
				+ uuid
				+ "\\\"></cybox:Observable_Package_Source><cybox:Title>Rosapa Profile</cybox:Title><cybox:Observable id=\\\"Profile-AnyInbound-KeyEvent\\\"><cybox:Description> Origin Conditions for the profile that detects suspicious activity on the workstation assuming that host in a secure environment.  </cybox:Description> <cybox:Keywords><cybox:Keyword>Type:Origins</cybox:Keyword></cybox:Keywords><cybox:Observable_Composition operator=\\\"AND\\\"><!-- any process accepts any inbound connection --><cybox:Observable idref=\\\"Rosapa:AnyInbound-cc789942-493b-486e-bd9e-5dc5808fb1bf\\\"><cybox:Keywords><cybox:Keyword>Impact:20</cybox:Keyword></cybox:Keywords></cybox:Observable></cybox:Observable_Composition></cybox:Observable><cybox:Observable id=\\\"Rosapa-KeyEvent-Profile-Test-FileWrite\\\"><cybox:Description> Origin Conditions for the profile that detects suspicious activity on the workstation assuming that host in a secure environment.  </cybox:Description> <cybox:Keywords><cybox:Keyword>Type:KeyEvents</cybox:Keyword></cybox:Keywords><cybox:Observable_Composition operator=\\\"AND\\\"><!-- Inbound exceutable key event --><cybox:Observable idref=\\\"Rosapa:FileWrite-f429f38f-e37a-4dd3-98ab-4809d73801f5\\\"><cybox:Keywords><cybox:Keyword>Impact:10</cybox:Keyword></cybox:Keywords></cybox:Observable><cybox:Observable idref=\\\"Rosapa:RegWrite-a585919c-1d07-4d5d-a781-0e58dd56d9f1\\\"><cybox:Keywords><cybox:Keyword>Impact:10</cybox:Keyword></cybox:Keywords></cybox:Observable></cybox:Observable_Composition></cybox:Observable></cybox:Observables>\"}";

		// Rosapa-AnyInbound-FileRegistry-Write-"+uuid
		String profilecondRes = HttpClientUtils.composePostRequest("https://"
				+ Configuration.getProperty("sentinelehost")
				+ ":9090/api/v1/profiles", payloadProfConditions);

		// System.out.println("manual root  response>>>" + manualRootRes);

		JSONObject prconObj = new JSONObject(profilecondRes);

		String condproid = prconObj.optString("id");

		if (condproid == null || condproid.trim() == "") {

			System.out
					.println("Creation of  Profile with  conditions------------->Fail");
			testCaseResult
					.append("Creation of  Profile with  conditions------------->Fail \n");

		} else {

			System.out
					.println("Creation of  Profile with  conditions------------->Pass");
			testCaseResult
					.append("Creation of  Profile with  conditions------------->Pass \n");

			System.out.println("Profile with conditions ID---------->"
					+ condproid);

			testCaseResult.append("Profile with conditions ID---------->"
					+ condproid + "\n");

		}

		// installing agent on endpoint

		// initialising ssh to virtual machines

		// System.out.println("ip>>>" + endPointMachine.getGuest().ipAddress);

		final SSHManager endpointSsh = new SSHManager(vmUser, vmPassword,
				endptIp);
		endpointSsh.connect();

		// install agent

		endpointSsh.copyFile(Configuration.getProperty("driverpath"),
				"CounterTack Agent Installer Hiding.exe");

		if (isXpmachine) {
			endpointSsh
					.runCommand("cmd /c \"C:\\Documents and Settings\\"
							+ vmUser
							+ "\\CounterTack Agent Installer Hiding.exe\" /S /HOST:"
							+ sentenelIp + " /PORT:443");

		} else {

			endpointSsh
					.runCommand("cmd /c \"C:\\Users\\"
							+ vmUser
							+ "\\CounterTack Agent Installer Hiding.exe\" /S /HOST:"
							+ sentenelIp + " /PORT:443");

		}

		System.out.println("Installing agent on endpoint");
		Thread.sleep(120000);

		String eId = null;
		ResultSet endpointIdRes = iConnector
				.executeQueryAndReturnResults("select id from endpoints where ip='"
						+ endptIp
						+ "'"
						+ " and status='ON' and ip is not null order by time_started desc limit 1");

		while (endpointIdRes.next()) {
			try {
				eId = endpointIdRes.getString(1);
			} catch (Exception e) {

			}

			System.out.println("endpoint Id>>>>>>" + eId);

		}

		if (eId == null) {

			System.out.println("Endpoint Installation-------------->Fail");
			testCaseResult
					.append("Endpoint Installation-------------->Fail \n");
			addResultsToLog(testCaseResult);

			System.exit(0);

		} else {

			System.out.println("Endpoint Installation---------------->Pass");
			testCaseResult
					.append("Endpoint Installation---------------->Pass \n");
			String kernalModVersion = getDriverVersion(eId, iConnector);
			testCaseResult.append("Kernal Module Version>>>>>> "
					+ kernalModVersion + "\n");

		}
		testCaseResult.append("Sentinel ip>>>>>> " + sentenelIp + "\n");
		testCaseResult.append("VM Name>>>>>> "
				+ Configuration.getProperty("vmname") + "\n");

		testCaseResult.append("VM IP>>>>>> " + endptIp + "\n");

		// getting default profile
		ResultSet defaultProfileRset = iConnector
				.executeQueryAndReturnResults("select cp from endpoints where id='"
						+ eId + "'");
		String defaultProfile = null;

		while (defaultProfileRset.next()) {
			String currentProfile = defaultProfileRset.getString(1);

			if (currentProfile != null) {

				defaultProfile = currentProfile;

			}
		}

		// adding endpoint to group

		// add endpoint to manual group

		String payloadAddendPntToGroup = "{\"type\": \"add_endpoints_to_group\",\"endpoints\":[\""
				+ eId + "\"]}";

		HttpClientUtils.composePostRequest(
				Configuration.getProperty("restapirooturi") + "/groups/"
						+ mrootgrpId + "/command", payloadAddendPntToGroup);

		Thread.sleep(60000);

		// verifying manual group

		ResultSet manualgrpEndpoints = iConnector
				.executeQueryAndReturnResults("select endpoints from groups where id='"
						+ mrootgrpId + "'");
		boolean ismanualGroupWorks = false;

		while (manualgrpEndpoints.next()) {
			String endpoints = manualgrpEndpoints.getString(1);

			if (endpoints != null) {

				// System.out.println("manual group endpoints>>>" + endpoints);
				if (endpoints.contains(eId)) {

					// System.out.println("Inbound passed");
					ismanualGroupWorks = true;
					break;
					// System.exit(0);
					// return;

				}

			}
		}

		if (ismanualGroupWorks) {
			System.out
					.println("Verifying manual group(Adding endpoint to manual group)-------->Pass");
			testCaseResult
					.append("Verifying manual group(Adding endpoint to manual group)-------->Pass \n");
		} else {

			System.out
					.println("Verifying manual group(Adding endpoint to manual group)-------->Fail");
			testCaseResult
					.append("Verifying manual group(Adding endpoint to manual group)-------->Fail \n");
		}

		//

		String payloadconditionNoorigin = "{\"type\":\"condition\",\"isNew\":true,\"is_user_visible\":true,\"is_user_editable\":true,\"is_validated_xml\":true,\"xml_string\":\"<cybox:Observables xmlns:countertack=\\\"https://www.countertack.com\\\" xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns:cybox=\\\"http://cybox.mitre.org/cybox-2\\\" xmlns:cyboxCommon=\\\"http://cybox.mitre.org/common-2\\\" xmlns:AddressObj=\\\"http://cybox.mitre.org/objects#AddressObject-2\\\" xmlns:PortObj=\\\"http://cybox.mitre.org/objects#PortObject-2\\\" xmlns:SocketAddressObj=\\\"http://cybox.mitre.org/objects#SocketAddressObject-1\\\"  xmlns:NetworkConnectionObj=\\\"http://cybox.mitre.org/objects#NetworkConnectionObject-2\\\" xmlns:example=\\\"http://example.com/\\\" xmlns:ProcessObj=\\\"http://cybox.mitre.org/objects#ProcessObject-2\\\" xmlns:cyboxVocabs=\\\"http://cybox.mitre.org/default_vocabularies-2\\\" xsi:schemaLocation=\\\"http://cybox.mitre.org/cybox-2 http://cybox.mitre.org/XMLSchema/core/2.0.1/cybox_core.xsd     http://cybox.mitre.org/objects#NetworkConnectionObject-2 http://cybox.mitre.org/XMLSchema/objects/Network_Connection/2.0.1/Network_Connection_Object.xsd   http://cybox.mitre.org/objects#ProcessObject-2  http://cybox.mitre.org/XMLSchema/objects/Process/2.0.1/Process_Object.xsd  http://cybox.mitre.org/default_vocabularies-2   http://cybox.mitre.org/XMLSchema/default_vocabularies/2.0.1/cybox_default_vocabularies.xsd   \\\" cybox_major_version=\\\"2\\\" cybox_minor_version=\\\"0\\\"> <cybox:Observable id=\\\"Sanjay-Inbound:observable-cc789942-493b-486e-bd9e-5dc5808fb1bf\\\"><cybox:Title>Ramana Any Inbound Condition</cybox:Title><cybox:Description>            This condition detects when svchost.exe process accepts inbound connection from any remote host.         </cybox:Description>       <cybox:Keywords><cybox:Keyword>Type:Condition</cybox:Keyword></cybox:Keywords>        <cybox:Event id=\\\"event-test-any-inbound\\\"><cybox:Actions><cybox:Action id=\\\"action-test-any-inbound\\\"><cybox:Type xsi:type=\\\"cyboxVocabs:ActionTypeVocab-1.0\\\">Accept</cybox:Type><cybox:Name xsi:type=\\\"cyboxVocabs:ActionNameVocab-1.0\\\">Accept Socket Connection</cybox:Name><cybox:Associated_Objects><cybox:Associated_Object><cybox:Properties xsi:type=\\\"NetworkConnectionObj:NetworkConnectionObjectType\\\"><NetworkConnectionObj:Destination_Socket_Address><SocketAddressObj:IP_Address><AddressObj:Address_Value pattern_type=\\\"Regex\\\"></AddressObj:Address_Value></SocketAddressObj:IP_Address><SocketAddressObj:Port><PortObj:Port_Value pattern_type=\\\"Regex\\\"></PortObj:Port_Value></SocketAddressObj:Port></NetworkConnectionObj:Destination_Socket_Address></cybox:Properties><cybox:Association_Type xsi:type=\\\"cyboxVocabs:ActionObjectAssociationTypeVocab-1.0\\\">Initiating</cybox:Association_Type></cybox:Associated_Object><cybox:Associated_Object><cybox:Properties xsi:type=\\\"ProcessObj:ProcessObjectType\\\"><ProcessObj:Name pattern_type=\\\"Regex\\\"></ProcessObj:Name></cybox:Properties><cybox:Association_Type xsi:type=\\\"cyboxVocabs:ActionObjectAssociationTypeVocab-1.0\\\">Returned</cybox:Association_Type></cybox:Associated_Object></cybox:Associated_Objects></cybox:Action></cybox:Actions></cybox:Event></cybox:Observable></cybox:Observables>\"}";

		String noorigincondRes = HttpClientUtils.composePostRequest("https://"
				+ Configuration.getProperty("sentinelehost")
				+ ":9090/api/v1/profiles", payloadconditionNoorigin);

		System.out.println("Noorigin condition response >>" + noorigincondRes);

		String payloadnooriginconProfile = "{\"type\":\"profile\",\"isNew\":true,\"is_user_visible\":true,\"is_user_editable\":true,\"is_validated_xml\":true,\"xml_string\":\"<cybox:Observables  xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns:countertack=\\\"https://www.countertack.com\\\" xmlns:cybox=\\\"http://cybox.mitre.org/cybox-2\\\" xmlns:cyboxCommon=\\\"http://cybox.mitre.org/common-2\\\" xmlns:FileObj=\\\"http://cybox.mitre.org/objects#FileObject-2\\\"  xmlns:ProcessObj=\\\"http://cybox.mitre.org/objects#ProcessObject-2\\\"  xmlns:cyboxVocabs=\\\"http://cybox.mitre.org/default_vocabularies-2\\\" xmlns:example=\\\"http://example.com\\\" xsi:schemaLocation=\\\"http://cybox.mitre.org/cybox-2 http://cybox.mitre.org/XMLSchema/core/2.0.1/cybox_core.xsd     http://cybox.mitre.org/objects#ProcessObject-2 http://cybox.mitre.org/XMLSchema/objects/Process/2.0.1/Process_Object.xsd     http://cybox.mitre.org/default_vocabularies-2 http://cybox.mitre.org/XMLSchema/default_vocabularies/2.0.1/cybox_default_vocabularies.xsd     \\\" cybox_major_version=\\\"2\\\" cybox_minor_version=\\\"0\\\"><cybox:Observable_Package_Source name=\\\"Profile-noorigincondition-"
				+ uuid
				+ "\\\"></cybox:Observable_Package_Source><cybox:Title>Ramana Inbound Profile</cybox:Title><cybox:Observable id=\\\"No-Origins-Profile-Test-AnyInbound\\\"><cybox:Description>Origin Conditions for the profile that detects suspicious activity on the workstation assuming that host in a secure environment. </cybox:Description><cybox:Keywords><cybox:Keyword>Type:BasicEvents</cybox:Keyword></cybox:Keywords><cybox:Observable_Composition operator=\\\"OR\\\"><!-- any process accepts any inbound connection --><cybox:Observable idref=\\\"Sanjay-Inbound:observable-cc789942-493b-486e-bd9e-5dc5808fb1bf\\\"><cybox:Keywords><cybox:Keyword>Impact:20</cybox:Keyword></cybox:Keywords></cybox:Observable></cybox:Observable_Composition></cybox:Observable></cybox:Observables>\"}";

		String profilenoorigincondRes = HttpClientUtils.composePostRequest(
				"https://" + Configuration.getProperty("sentinelehost")
						+ ":9090/api/v1/profiles", payloadnooriginconProfile);

		// System.out.println("manual root  response>>>" + manualRootRes);

		JSONObject prnooriginconObj = new JSONObject(profilenoorigincondRes);

		String noorigincondproid = prnooriginconObj.optString("id");

		if (noorigincondproid == null || noorigincondproid.trim() == "") {

			System.out
					.println("Creation of  Profile with  no origin condition------------->Fail");
			testCaseResult
					.append("Creation of  Profile with  no origin condition------------->Fail \n");

		} else {

			System.out
					.println("Creation of  Profile with no origin condition------------->Pass");
			testCaseResult
					.append("Creation of  Profile with no origin condition------------->Pass \n");

			System.out.println("Profile with no origin condition ID---------->"
					+ noorigincondproid);

			testCaseResult
					.append("Profile with no origin condition ID---------->"
							+ noorigincondproid);

		}

		pauseEndpoint(eId);
		Thread.sleep(60000);

		// applying profile to endpoint

		String payload = "{ " + "  \"type\": \"apply_profile_to_endpoints\", "
				+ "  \"profile\":\"Rosapa-AnyInbound-FileRegistry-Write-"
				+ uuid + "\", " + "  \"endpoints\":[ " + "\"" + eId + "\" "
				+ "] " + "} ";
		System.out.println("payload>>>" + payload);
		//

		HttpClientUtils.composePostRequest(
				Configuration.getProperty("restapirooturi")
						+ "/endpoints/command", payload);

		Thread.sleep(3000);
		pauseEndpoint(eId);

		Thread.sleep(60000);
		resumeEndpoint(eId);
		Thread.sleep(60000);

		ResultSet currentProfileRset = iConnector
				.executeQueryAndReturnResults("select cp from endpoints where id='"
						+ eId + "'");
		boolean isProfilechanged = false;

		while (currentProfileRset.next()) {
			String currentProfile = currentProfileRset.getString(1);

			if (currentProfile != null) {

				// System.out.println("Current Profile>>>" + currentProfile);
				if (currentProfile.contains(condproid)) {

					// System.out.println("Inbound passed");
					isProfilechanged = true;
					break;
					// System.exit(0);
					// return;

				}

			}
		}

		if (isProfilechanged) {
			System.out.println("Changing Profile-------->Pass");
			testCaseResult.append("Changing Profile-------->Pass \n");
			System.out.println("Verifying Profile updation-------->Pass");
			testCaseResult.append("Verifying Profile updation-------->Pass \n");
		} else {

			System.out.println("Changing Profile-------->Fail");
			testCaseResult.append("Changing Profile-------->Fail \n");
			System.out.println("Verifying Profile updation-------->Fail");
			testCaseResult.append("Verifying Profile updation-------->Fail \n");
		}

		resumeEndpoint(eId);

		Thread.sleep(30000);
		endpointSsh.runCommand("cmd /c ipconfig > c:\\Users\\user\\test_file"
				+ uuid + ".txt");
		endpointSsh
				.runCommand("cmd /c netstat -na > c:\\Users\\user\\test_file"
						+ uuid + ".txt");
		endpointSsh
				.runCommand("cmd /c reg  add HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\sshdkey"
						+ uuid);

		Thread.sleep(10000);

		ResultSet brs = iConnector
				.executeQueryAndReturnResults("select hex(id) from behaviors where uri like '%"
						+ eId + "%'  order by event_start_time desc limit 1");
		String bhid = null;

		while (brs.next()) {
			bhid = brs.getString(1);

		}
		// System.out.println("behavior id>>>>" + bhid);

		// verifying netcat client
		ResultSet netcatpros = iConnector
				.executeQueryAndReturnResults("select target_thread_process_name from behaviors_denorm where hex(behavior_id)='"
						+ bhid
						+ "' and behavior_id is not null and is_origin=1");
		boolean inbound = false;
		while (netcatpros.next()) {
			String path = netcatpros.getString(1);

			if (path != null) {

				// System.out.println("path>>>" + path);
				if (path.contains("FreeSSHD")) {

					// System.out.println("Inbound passed");
					inbound = true;
					break;
					// System.exit(0);
					// return;

				}

			}
		}

		if (inbound) {

			System.out.println("New origin for Inbound(SSH)---------->Pass");
			testCaseResult
					.append("New origin for Inbound(SSH)---------->Pass \n");

		} else {

			System.out.println("New origin for Inbound(SSH)---------->Fail");
			testCaseResult
					.append("New origin for Inbound(SSH)---------->Fail \n");

		}
		ResultSet flwrrs = iConnector
				.executeQueryAndReturnResults("select target_file_path from behaviors_denorm where hex(behavior_id) = '"
						+ bhid
						+ "' and behavior_id is not null and is_key=1 group by target_file_path");
		boolean fwrite = false;
		while (flwrrs.next()) {
			String fn = flwrrs.getString(1);

			if (fn != null) {

				System.out.println("fname>>>" + fn);
				if (fn.contains("test_file" + uuid + ".txt")) {

					// System.out.println("Inbound passed");
					fwrite = true;
					break;
					// System.exit(0);
					// return;

				}

			}
		}

		if (fwrite) {

			System.out.println("New Key event for file write------->Pass");
			testCaseResult
					.append("New Key event for file write------->Pass \n");

		} else {

			System.out.println("New Key event for file write------->Fail");
			testCaseResult
					.append("New Key event for file write------->Fail \n");

		}

		pauseEndpoint(eId);
		Thread.sleep(60000);

		// applying profile to endpoint

		String payloadChngToDefPro = "{ "
				+ "  \"type\": \"apply_profile_to_endpoints\", "
				+ "  \"profile\":\"" + defaultProfile + "\", "
				+ "  \"endpoints\":[ " + "\"" + eId + "\" " + "] " + "} ";
		// System.out.println("payload>>>" + payload);
		//

		HttpClientUtils.composePostRequest(
				Configuration.getProperty("restapirooturi")
						+ "/endpoints/command", payloadChngToDefPro);

		Thread.sleep(3000);
		pauseEndpoint(eId);

		Thread.sleep(60000);
		resumeEndpoint(eId);
		Thread.sleep(60000);

		String malwaresPath = "darkseoul.exe";
		runMalwareTest(esxiConnector, iConnector, sentenelIp, malwaresPath);
		addResultsToLog(testCaseResult);
		// System.exit(0);

	}

	public static void addResultsToLog(StringBuffer vals) {
		File testCaseResFile = new File("tba_result_"
				+ Configuration.getProperty("vmname") + ".txt");

		try {
			testCaseResFile.createNewFile();
			FileOutputStream fout = new FileOutputStream(testCaseResFile);

			//

			fout.write(vals.toString().getBytes());

			fout.flush();
			fout.close();

		} catch (Exception e) {

			e.printStackTrace();

		}

	}

	public static void runMalwareTest(VMWareConnector esxiConnector,
			ImpalaConnector iConnector, String sentenelIp, String malwaresPath)
			throws Exception {
		// String endptIp = "10.140.62.159";

		final VirtualMachine endPointMachine = esxiConnector
				.getVirtualMachineByname(Configuration.getProperty("vmname"));

		// win7x64-sym-2
		System.out.println("power state >>>"
				+ endPointMachine.getRuntime().powerState);

		String endpointMachineStatus = esxiConnector
				.getVirtualMachineStatus(endPointMachine);

		if (endpointMachineStatus == null) {

			System.out.println("Power on  endpoint machine .....");

			esxiConnector.startVirtualMachine(endPointMachine);

			Thread.sleep(600000);

		} else {

			if ("notRunning".equalsIgnoreCase(endpointMachineStatus)) {

				esxiConnector.reStartVirtualMachine(endPointMachine);

				System.out.println("Rebooting endpoint machine .....");

				Thread.sleep(600000);

			}

		}

		// initialising ssh to virtual machines
		String endptIp = Configuration.getProperty("vmip");
		if (endptIp == null || endptIp.trim() == "") {

			endptIp = endPointMachine.getGuest().ipAddress;
		}
		System.out.println("ip>>>" + endptIp);

		SSHManager endpointSsh = new SSHManager(vmUser, vmPassword, endptIp);
		endpointSsh.connect();

		String eId = null;
		ResultSet endpointIdRes = iConnector
				.executeQueryAndReturnResults("select id from endpoints where ip='"
						+ endptIp
						+ "'"
						+ " and status='ON' order by time_started desc limit 1");

		while (endpointIdRes.next()) {
			try {
				eId = endpointIdRes.getString(1);
			} catch (Exception e) {

			}

			System.out.println("endpoint Id>>>>>>" + eId);

		}

		if (eId == null) {

			System.out.println("endpoint is not installed");

			return;

		}

		pauseEndpoint(eId);
		Thread.sleep(60000);
		File malwaref = new File(malwaresPath);
		System.out.println("malware mname>>>" + malwaref.getName());

		String malwareTestString = malwaref.getName();
		if (malwaref.getName().length() > 4) {

			malwareTestString = malwaref.getName().substring(0, 4);

		}
		endpointSsh.copyFile(malwaresPath, malwaref.getName());

		Thread.sleep(6000);
		System.out.println("malware copied success fully");

		resumeEndpoint(eId);

		Thread.sleep(60000);

		try {
			if(isXpmachine){
				endpointSsh.runCommand("cmd /c \"C:\\Documents and Settings\\" + vmUser + "\\"
						+ malwaref.getName()+"\"");
				
			}else{
				
				
				endpointSsh.runCommand("cmd /c \"C:\\Users\\" + vmUser + "\\"
						+ malwaref.getName()+"\"");	
			}

			System.out.println("malware installed...");

		} catch (Exception e) {

		}
		boolean isbsod = false;
		endpointMachineStatus = esxiConnector
				.getVirtualMachineStatus(endPointMachine);
		if ("Running".equalsIgnoreCase(endpointMachineStatus)) {

			String bsodRes = endpointSsh
					.returnCommandOutPut("cmd /c cd C:\\Windows && dir /b /a-d");

			if (bsodRes != null) {

				if (bsodRes.contains("MEMORY.dump")) {

					isbsod = true;

				}

			}
		}
		Thread.sleep(1500000);

		// retriving behavior id

		ResultSet brs = iConnector
				.executeQueryAndReturnResults("select hex(id) from behaviors where uri like '%"
						+ eId + "%'  order by event_start_time desc limit 1");
		String bhid = null;
		boolean isMalwareTriggered = false;
		while (brs.next()) {
			bhid = brs.getString(1);

		}
		System.out.println("behavior id>>>>" + bhid);
		StringBuffer resultBuffer = new StringBuffer();
		resultBuffer.append("Sentinel ip>>>>>> " + sentenelIp + "\n");
		resultBuffer.append("VM Name>>>>>> "
				+ Configuration.getProperty("vmname") + "\n");

		resultBuffer.append("VM IP>>>>>> " + endptIp + "\n");
		resultBuffer.append("Kernal Module>>>>>> "
				+ getDriverVersion(eId, iConnector) + "\n");
		resultBuffer.append("Behavior id :::::" + bhid + "\n");
		int no_of_files = 0;
		int no_of_registries = 0;
		int no_of_processes = 0;
		int notification_count = 0;
		int key_event_count = 0;
		int event_count = 0;
		int behavior_count = 0;
		int basic_event_count = 0;

		if (bhid != null) {

			ResultSet ressProcess = iConnector
					.executeQueryAndReturnResults("select target_process_name from behaviors_denorm where hex(behavior_id) = '"
							+ bhid + "' and behavior_id is not null");
			resultBuffer.append("Processes Names-----------> \n");

			while (ressProcess.next()) {
				String processName = ressProcess.getString(1);

				if (processName != null) {

					if (processName.contains(malwareTestString)) {

						isMalwareTriggered = true;

					}
					resultBuffer.append(processName + "\n");
					no_of_processes++;
					System.out.println("Process name>>>" + processName);

				}
			}

			ResultSet flwrrs = iConnector
					.executeQueryAndReturnResults("select target_file_path from behaviors_denorm where hex(behavior_id) = '"
							+ bhid + "' and behavior_id is not null");
			resultBuffer.append("File Names-----------> \n");
			while (flwrrs.next()) {
				String fn = flwrrs.getString(1);

				if (fn != null) {
					resultBuffer.append(fn + "\n");
					System.out.println("file name>>>" + fn);
					no_of_files++;

				}
			}

			ResultSet regwrrs = iConnector
					.executeQueryAndReturnResults("select target_registry_key from behaviors_denorm where hex(behavior_id) = '"
							+ bhid + "' and behavior_id is not null");
			// regkey
			resultBuffer.append("Registry Keys-----------> \n");
			while (regwrrs.next()) {
				String rn = regwrrs.getString(1);

				if (rn != null) {
					resultBuffer.append(rn + "\n");
					System.out.println("Reg Key>>>" + rn);
					no_of_registries++;

				}
			}

		}

		ResultSet clsrs = iConnector
				.executeQueryAndReturnResults("select classification_name,endpoint_id from classified_endpoints where endpoint_id='"
						+ eId + "'");
		boolean clsoc = false;
		String clsName = null;
		String clsGroup = "";
		while (clsrs.next()) {
			clsName = clsrs.getString(1);

			if (clsName != null) {
				System.out.println("classification_name>>>" + clsName);
				clsoc = true;
				clsGroup = clsGroup + "_" + clsName;
				// break;

			}
		}
		clsName = clsGroup;

		if (clsName.startsWith("_")) {

			clsName = clsName.replaceFirst("_", "");
		}

		if (clsoc) {

			System.out.println("Malware test result -------->Pass");
		} else {

			System.out.println("Malware test result ---------->Fail");

		}

		try {
			ResultSet countRs = iConnector
					.executeQueryAndReturnResults("select notification_count,key_event_count,event_count,behavior_count,basic_event_count from endpoints where id='"
							+ eId + "'");

			while (countRs.next()) {
				try {
					notification_count = countRs.getInt(1);
					key_event_count = countRs.getInt(2);
					event_count = countRs.getInt(3);
					behavior_count = countRs.getInt(4);
					basic_event_count = countRs.getInt(5);
				} catch (Exception e) {

					e.printStackTrace();

				}

			}

		} catch (Exception e1) {

			e1.printStackTrace();

		}

		String malName = malwaref.getName();

		malName = malName.replaceAll("\\.", "_");

		File malResultFile = new File("tba_malaware_result_"
				+ Configuration.getProperty("vmname") + "_" + malName + ".txt");

		malResultFile.createNewFile();
		try {
			FileOutputStream fout = new FileOutputStream(malResultFile);
			resultBuffer.append("Malware behavior status:" + isMalwareTriggered
					+ "\n");
			resultBuffer
					.append("Malware classification name:" + clsName + "\n");
			resultBuffer.append("BSOD:" + isbsod + "\n");

			resultBuffer.append("Number of Files:" + no_of_files + "\n");

			resultBuffer.append("Number of Regestries:" + no_of_registries
					+ "\n");

			resultBuffer
					.append("Number of Processes:" + no_of_processes + "\n");
			resultBuffer
					.append("Number of Keyevents:" + key_event_count + "\n");

			resultBuffer.append("Number of events:" + event_count + "\n");

			//

			fout.write(resultBuffer.toString().getBytes());

			fout.flush();
			fout.close();

		} catch (Exception e) {

			e.printStackTrace();

		}
		uninstallEndPoint(eId);
		Thread.sleep(60000);
		// reverting to snap shot

		endPointMachine.revertToCurrentSnapshot_Task(null);

		Thread.sleep(480000);

	}

	public static void pauseEndpoint(String eid) throws Exception {

		String pause = "{ " + "  \"type\":\"pause_many\", "
				+ "  \"endpoints\":[ " + "\"" + eid + "\" " + " ] " + "} ";

		HttpClientUtils.composePostRequest(
				Configuration.getProperty("restapirooturi")
						+ "/endpoints/command", pause);

	}

	public static void resumeEndpoint(String eid) throws Exception {

		String resume = "{ " + "  \"type\":\"resume_many\", "
				+ "  \"endpoints\":[ " + "    \"" + eid + "\" " + "] " + "} ";

		HttpClientUtils.composePostRequest(
				Configuration.getProperty("restapirooturi")
						+ "/endpoints/command", resume);

	}

	public static void uninstallEndPoint(String eid) throws Exception {

		String uninstall = "{ " + "  \"type\":\"uninstall_many\", "
				+ "  \"endpoints\":[ " + "    \"" + eid + "\" " + "] " + "} ";

		HttpClientUtils.composePostRequest(
				Configuration.getProperty("restapirooturi")
						+ "/endpoints/command", uninstall);

	}

	public static void main1(String[] args) throws Exception {
		String uuid = UUID.randomUUID().toString();
		String configFilePath = "C:\\Users\\user\\Desktop\\config.properties";

		Configuration.loadProperties(configFilePath);
		String payloadProfConditions = "{\"type\":\"profile\",\"isNew\":true,\"is_user_visible\":true,\"is_user_editable\":true,\"is_validated_xml\":true,\"xml_string\":\"<cybox:Observables xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns:countertack=\\\"https://www.countertack.com\\\" xmlns:cybox=\\\"http://cybox.mitre.org/cybox-2\\\" xmlns:cyboxCommon=\\\"http://cybox.mitre.org/common-2\\\" xmlns:FileObj=\\\"http://cybox.mitre.org/objects#FileObject-2\\\" xmlns:ProcessObj=\\\"http://cybox.mitre.org/objects#ProcessObject-2\\\" xmlns:cyboxVocabs=\\\"http://cybox.mitre.org/default_vocabularies-2\\\" xmlns:example=\\\"http://example.com\\\" xsi:schemaLocation=\\\"http://cybox.mitre.org/cybox-2 http://cybox.mitre.org/XMLSchema/core/2.0.1/cybox_core.xsd http://cybox.mitre.org/objects#ProcessObject-2 http://cybox.mitre.org/XMLSchema/objects/Process/2.0.1/Process_Object.xsd http://cybox.mitre.org/default_vocabularies-2 http://cybox.mitre.org/XMLSchema/default_vocabularies/2.0.1/cybox_default_vocabularies.xsd \\\" cybox_major_version=\\\"2\\\" cybox_minor_version=\\\"0\\\"><cybox:Observable_Package_Source name=\\\"Rosapa-AnyInbound-FileRegistry-Write-"
				+ uuid
				+ "\\\"></cybox:Observable_Package_Source><cybox:Title>Rosapa Profile</cybox:Title><cybox:Observable id=\\\"Profile-AnyInbound-KeyEvent\\\"><cybox:Description> Origin Conditions for the profile that detects suspicious activity on the workstation assuming that host in a secure environment.  </cybox:Description> <cybox:Keywords><cybox:Keyword>Type:Origins</cybox:Keyword></cybox:Keywords><cybox:Observable_Composition operator=\\\"AND\\\"><!-- any process accepts any inbound connection --><cybox:Observable idref=\\\"Rosapa:AnyInbound-cc789942-493b-486e-bd9e-5dc5808fb1bf\\\"><cybox:Keywords><cybox:Keyword>Impact:20</cybox:Keyword></cybox:Keywords></cybox:Observable></cybox:Observable_Composition></cybox:Observable><cybox:Observable id=\\\"Rosapa-KeyEvent-Profile-Test-FileWrite\\\"><cybox:Description> Origin Conditions for the profile that detects suspicious activity on the workstation assuming that host in a secure environment.  </cybox:Description> <cybox:Keywords><cybox:Keyword>Type:KeyEvents</cybox:Keyword></cybox:Keywords><cybox:Observable_Composition operator=\\\"AND\\\"><!-- Inbound exceutable key event --><cybox:Observable idref=\\\"Rosapa:FileWrite-f429f38f-e37a-4dd3-98ab-4809d73801f5\\\"><cybox:Keywords><cybox:Keyword>Impact:10</cybox:Keyword></cybox:Keywords></cybox:Observable><cybox:Observable idref=\\\"Rosapa:RegWrite-a585919c-1d07-4d5d-a781-0e58dd56d9f1\\\"><cybox:Keywords><cybox:Keyword>Impact:10</cybox:Keyword></cybox:Keywords></cybox:Observable></cybox:Observable_Composition></cybox:Observable></cybox:Observables>\"}";

		// Rosapa-AnyInbound-FileRegistry-Write-"+uuid
		String profilecondRes = HttpClientUtils.composePostRequest("https://"
				+ Configuration.getProperty("sentinelehost")
				+ ":9090/api/v1/profiles", payloadProfConditions);

		// System.out.println("manual root  response>>>" + manualRootRes);

		JSONObject prconObj = new JSONObject(profilecondRes);

		String condproid = prconObj.optString("id");

		if (condproid == null || condproid.trim() == "") {

			System.out
					.println("Creation of  Profile with  conditions------------->Fail");

		} else {

			System.out
					.println("Creation of  Profile with  conditions------------->Pass");

			System.out.println("Profile with conditions ID---------->"
					+ condproid);

		}

		// applying profile to endpoint

		String payload = "{ " + "  \"type\": \"apply_profile_to_endpoints\", "
				+ "  \"profile\":\"Rosapa-AnyInbound-FileRegistry-Write-"
				+ uuid + "\", " + "  \"endpoints\":[ " + "\"" + 1 + "\" "
				+ "] " + "} ";
		// System.out.println("payload>>>" + payload);
		//

		HttpClientUtils.composePostRequest(
				Configuration.getProperty("restapirooturi")
						+ "/endpoints/command", payload);

	}

	public static String getDriverVersion(String eid, ImpalaConnector iConnector) {

		String driver_Version = null;
		ResultSet endpointStatRes = iConnector
				.executeQueryAndReturnResults("select driver_version from endpoints where id='"
						+ eid + "'");
		try {
			while (endpointStatRes.next()) {
				try {
					driver_Version = endpointStatRes.getString(1);
				} catch (Exception e) {

				}

				System.out.println("Driver version>>>>>>" + driver_Version);

			}
		} catch (Exception e) {

		}

		return driver_Version;

	}

}
